// composables/useSubscribeMessage.js
import { ref } from 'vue'

/**
 * 订阅消息 Hook
 * @param {Array} templateIds - 模板ID列表
 * @param {Object} options - 配置选项
 * @returns {Object} 订阅消息相关方法和状态
 */
export const useSubscribeMessage = (templateIds = [], options = {}) => {
    // 默认配置
    const config = {
        forceSubscribe: false, // 是否强制订阅
        autoCheckStatus: true, // 是否自动检查订阅状态
        ...options
    }
    
    // 响应式数据
    const templateIdList = ref([...templateIds])
    const hasSubscribed = ref(false)
    const isLoading = ref(false)
    const authStatus = ref(null)
    const subscriptionSetting = ref(null)
    const showReAuthTip = ref(false)
    
    /**
     * 检查用户订阅消息状态
     */
    const checkSubscriptionStatus = () => {
        if (!uni.getSetting) return
        
        return new Promise((resolve) => {
            uni.getSetting({
                withSubscriptions: true,
                success: (res) => {
                    console.log('订阅消息设置:', res.subscriptionsSetting)
                    subscriptionSetting.value = res.subscriptionsSetting
                    
                    if (res.subscriptionsSetting && templateIdList.value.length > 0) {
                        const mainTemplateId = templateIdList.value[0]
                        const itemSetting = res.subscriptionsSetting.itemSettings || {}
                        hasSubscribed.value = itemSetting[mainTemplateId] === 'accept'
                        showReAuthTip.value = itemSetting[mainTemplateId] === 'reject'
                    }
                    resolve(res.subscriptionsSetting)
                },
                fail: (err) => {
                    console.error('获取订阅设置失败:', err)
                    resolve(null)
                }
            })
        })
    }
    
    /**
     * 请求订阅消息授权
     */
    const requestSubscribeMessage = () => {
        return new Promise((resolve, reject) => {
            if (!uni.requestSubscribeMessage) {
                uni.showModal({
                    title: '提示',
                    content: '当前微信版本过低，请升级后使用',
                    showCancel: false
                })
                reject(new Error('API not supported'))
                return
            }
            
            isLoading.value = true
            authStatus.value = null
            
            uni.requestSubscribeMessage({
                tmplIds: templateIdList.value,
                success: async (res) => {
                    console.log('订阅消息授权结果:', res)
                    isLoading.value = false
                    
                    // 检查所有模板的授权状态[1](@ref)
                    const allAccepted = templateIdList.value.some(tmplId => 
                        res[tmplId] === 'accept'
                    )
                    
                    if (allAccepted) {
                        hasSubscribed.value = true
                        showReAuthTip.value = false
                        authStatus.value = {
                            type: 'success',
                            message: '订阅消息授权成功'
                        }
                        resolve(res)
                    } else {
                        handleSubscribeReject(res)
                        resolve(false)
                    }
                },
                fail: (err) => {
                    isLoading.value = false
                    handleSubscribeError(err)
                    reject(err)
                }
            })
        })
    }
    
    /**
     * 处理订阅拒绝情况
     */
    const handleSubscribeReject = (res) => {
        const rejectedTemplates = templateIdList.value.filter(tmplId => 
            res[tmplId] === 'reject'
        )
        
        if (rejectedTemplates.length > 0) {
            showReAuthTip.value = true
            authStatus.value = {
                type: 'error',
                message: '订阅消息被拒绝'
            }
            
            if (config.forceSubscribe) {
                uni.showModal({
                    title: '授权提示',
                    content: '您拒绝了订阅消息授权，将无法正常使用。请授权后继续。',
                    confirmText: '重新授权',
                    cancelText: '取消',
                    success: (modalRes) => {
                        if (modalRes.confirm) {
                            setTimeout(() => {
                                requestSubscribeMessage()
                            }, 500)
                        }
                    }
                })
            }
        }
        
        return false
    }
    
    /**
     * 处理订阅错误
     */
    const handleSubscribeError = (err) => {
        console.error('订阅消息错误:', err)
        
        // 处理20004错误：用户关闭了主开关[2](@ref)
        if (err.errCode === 20004) {
            showReAuthTip.value = true
            uni.showModal({
                title: '订阅消息已关闭',
                content: '检测到您已关闭订阅消息权限，需要开启后才能使用。是否前往设置？',
                confirmText: '去设置',
                success: (res) => {
                    if (res.confirm) {
                        uni.openSetting({
                            success: (settingRes) => {
                                console.log('设置结果:', settingRes)
                                if (settingRes.authSetting && 
                                    settingRes.authSetting['scope.subscribeMessage']) {
                                    setTimeout(() => {
                                        requestSubscribeMessage()
                                    }, 500)
                                }
                            }
                        })
                    }
                }
            })
        } else {
            authStatus.value = {
                type: 'error',
                message: '授权失败，请重试'
            }
            uni.showToast({
                title: '授权失败，请重试',
                icon: 'none'
            })
        }
    }
    
    /**
     * 触发订阅消息（主要对外方法）
     */
    const triggerSubscribe = async () => {
        try {
            const result = await requestSubscribeMessage()
            return result
        } catch (error) {
            console.error('订阅消息触发失败:', error)
            throw error
        }
    }
    
    /**
     * 重置订阅状态
     */
    const resetSubscribeStatus = () => {
        hasSubscribed.value = false
        isLoading.value = false
        authStatus.value = null
        showReAuthTip.value = false
    }
    
    /**
     * 更新模板ID列表
     */
    const updateTemplateIds = (newTemplateIds) => {
        templateIdList.value = [...newTemplateIds]
    }
    
    // 自动检查订阅状态
    if (config.autoCheckStatus) {
        checkSubscriptionStatus()
    }
    
    return {
        // 状态
        hasSubscribed,
        isLoading,
        authStatus,
        subscriptionSetting,
        showReAuthTip,
        templateIdList,
        
        // 方法
        triggerSubscribe,
        checkSubscriptionStatus,
        resetSubscribeStatus,
        updateTemplateIds,
        requestSubscribeMessage
    }
}

export default useSubscribeMessage